import React, { FC, Fragment, useEffect, useState } from 'react';
import { Chart, Geom, Tooltip, Coord, Label } from 'bizcharts';

import {
  defaultColors,
  linearDefaultColors
} from "@/constants/chartColors";
import DataSet from '@antv/data-set';

import { mapData } from './mapData.js'

import styles from './index.less'
import * as turf from '@turf/turf';

// 显示九段线且无交互版：https://codesandbox.io/s/blissful-bird-1i1y5?file=/src/App.js

function keepMapRatio(mapData, c, type) {
  if (mapData && turf) {
    // 获取数据外接矩形，计算宽高比
    const bbox = turf.bbox(mapData);
    const width = bbox[2] - bbox[0];
    const height = bbox[3] - bbox[1];
    const ratio = height / width;

    const cWidth = c.get('width');
    const cHeight = c.get('height');
    const cRatio = cHeight / cWidth;
    const mapRatio = c.get('mapRatio');
    if (!cRatio || cRatio === mapRatio) return;

    if (cRatio >= ratio) {
      const halfDisRatio = (cRatio - ratio) / 2 / cRatio;
      c.scale('x', {
        range: [0, 1],
      });
      c.scale('y', {
        range: [halfDisRatio, 1 - halfDisRatio],
      });
    } else {
      const halfDisRatio = ((1 / cRatio - 1 / ratio) / 2) * cRatio;
      c.scale('y', {
        range: [0, 1],
      });
      c.scale('x', {
        range: [halfDisRatio, 1 - halfDisRatio],
      });
    }

    c.set('mapRatio', cRatio);
    c.repaint();
  }
}

const colors = '#bfc5e0,#a2bdb9,#41ffd1,#2cd9d9,#3379dd'
  .split(',')

type BasicChart = {
  subTitle?: string,
  padding?: []
  height?: number
  mapValue?: any
}

const scale = {
  x: { sync: true },
  y: { sync: true },
};

const BasicColumn: FC<BasicChart> = props => {
  const {
    subTitle, mapValue = null, showSelfLegend = true,
    // chart 配置
    height = 260, padding = [10, 10, 10, 10],
  } = props;

  const [max, setMax] = useState(0)
  const [min, setMin] = useState(0)
  const [interval, setInterval] = useState(0)
  const [chartData, setChartData] = useState([])
  const [mapDataResult, setMapResultData] = useState()

  useEffect(() => {
    if (mapValue) {
      const feas = mapData.features.filter(feat => feat.properties.name).map(v => {
        return {
          ...v,
          properties: {
            ...v.properties,
            size: mapValue[v.properties.name] || 0,
          },
        };
      });
      const mapDataResult = { ...mapData, features: feas };
      setMapResultData(mapDataResult)
      // data set
      const ds = new DataSet();

      // draw the map
      const dv = ds
        .createView('back')
        .source(mapDataResult, {
          type: 'GeoJSON',
        })
        .transform({
          type: 'geo.projection',
          projection: 'geoMercator',
          as: ['x', 'y', 'centroidX', 'centroidY'],
        });

      const bgView = new DataSet.View().source(dv.rows);
      const sizes = bgView.rows.map(r => Number(r.properties.size));

      const min = Math.min(...sizes);
      const max = Math.max(...sizes);
      const interval = (max - min) / colors.length;
      setMax(max)
      setMin(min)
      setInterval(interval)
      setChartData(bgView)
      setMapResultData(mapDataResult)
    }
  }, [mapValue])
  return (
    <div className={styles['map-container']}>
      {subTitle ? <div className={styles.subtitle}>{subTitle}</div> : null}
      {
        mapDataResult &&
        <Chart
          height={height} data={chartData} forceFit padding={padding} scale={scale}
          onGetG2Instance={c => {
            keepMapRatio(mapDataResult, c, 'render');
            c.on('afterrender', () => {
              keepMapRatio(mapDataResult, c, 'rerender');
            });
            // 缩放交互，体验不好
            // c.interact('zoom', {
            //     type:'XY', // 设置缩放的类型，'X' x 轴方向缩放, 'Y' y 轴方向缩放, 'XY' x 和 y 轴同时缩放
            //     stepRatio: 0.05, // 控制缩放速度，默认值 0.05
            //     minScale: 1, // 最小缩放比例，默认值 1
            //     maxScale: 4, // 最大缩放比例，默认值 4
            //     catStep: 2 // 分类数据的缩放速度，默认值 2
            // });
          }}
        >
          <Coord reflect="y" />
          <Tooltip title="name" />
          <Geom
            type="polygon"
            position="x*y"
            style={{
              fill: '#DDDDDD',
              stroke: '#b1b1b1',
              lineWidth: 0.5,
              fillOpacity: 0.85,
            }}
            color={[
              'properties',
              p => {
                const idx = (Number(p.size) - min) / interval;
                return colors[Math.floor(idx) || 0];
              },
            ]}
            tooltip={[
              'name*properties',
              (t, p) => {
                return {
                  //自定义 tooltip 上显示的 title 显示内容等。
                  name: 'Size',
                  title: t,
                  value: p.size,
                };
              },
            ]}
          >
            <Label
              type="map"
              content="name"
              textStyle={{
                fill: '#666',
                fontWeight: 400,
                stroke: '#fff',
              }}
            />
          </Geom>
        </Chart>
      }
      {
        showSelfLegend &&
        <div className={styles['self-legend-container']}>
          <div className={styles['legend-title']}>
            <div>0</div>
            <div>5</div>
          </div>
          <div className={styles['legend-color']}>
            <div className={styles['legend-color-item']} style={{ background: colors[0] }}></div>
            <div className={styles['legend-color-item']} style={{ background: colors[1] }}></div>
            <div className={styles['legend-color-item']} style={{ background: colors[2] }}></div>
            <div className={styles['legend-color-item']} style={{ background: colors[3] }}></div>
            <div className={styles['legend-color-item']} style={{ background: colors[4] }}></div>
          </div>
          <div className={styles['legend-title']}>
            <div>企业投资比重</div>
          </div>
        </div>
      }
    </div>
  );
}

export default BasicColumn;
